package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.joda.time.LocalDateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MessageService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private AnnouncementApi announcementApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    //根据环信用户id,查询用户详情
    public UserInfoVo findUserInfoByHuanxin(String huanxinId) {
        //1. 根据环信id查询用户
        User user = userApi.findByHuanxin(huanxinId);
        //2. 根据用户id,查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());
        //3. 构建vo返回值
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);//只会copy同名同类型的属性
        if (userInfo.getAge() != null){
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加好友关系
    public void contacts(Long fiendId) {
        //1. 将好友关系注册到环信
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(),
                Constants.HX_USER_PREFIX + fiendId);
        if (!aBoolean){
            throw new BusinessException(ErrorResult.contactsError());
        }
        //2. 如果注册成功，记录好友关系到mongodb
        friendApi.save(UserHolder.getUserId(),fiendId);
    }

    //分页查询联系人列表
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //1. 调用API查询当前用户的好友数据 -- List<Friend>
        List<Friend> list = friendApi.friendByUserId(UserHolder.getUserId(),page,pagesize);
        if (CollUtil.isEmpty(list)){//如果没有好友，则返回空的联系人列表
            return new PageResult();
        }
        //2. 提取数据列表中的好友id
        List<Long> userIds = CollUtil.getFieldValues(list, "friendId", Long.class);
        //3. 调用UserInfoAPI查询好友的用户详情
        UserInfo info = new UserInfo();
        info.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, info);
        //4. 构造VO对象
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            UserInfo userInfo = map.get(friend.getFriendId());
            if (userInfo != null){
                ContactVo vo = ContactVo.init(userInfo);
                vos.add(vo);
            }
        }
        return new PageResult(page,pagesize,0l,vos);
    }

    //列表（分页查询） --- 列表分为：点赞列表、评论列表、喜欢列表，根据commentType类型进行区分
    public PageResult comments( Integer page, Integer pagesize,Integer commentType) {
        //1. 调用API查询当前用户的列表数据 --List<Comment>
        List<Comment> list = commentApi.CommentByUserId(UserHolder.getUserId(),page,pagesize,commentType);
        if (CollUtil.isEmpty(list)){//如果没有数据（点赞列表 或者 评论列表 或者 喜欢列表），则返回空
            return new PageResult();
        }
        //2. 提取列表中的评论人id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //3. 调用UserInfoAPI查询评论人的用户详情
        List<UserInfo> userInfos = userInfoApi.findByuserIds(userIds);
        //4. 构造VO对象
        List<CommentVo> vos = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            CommentVo vo = new CommentVo();
            BeanUtils.copyProperties(userInfo,vo);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0l,vos);
    }

    //公共列表（分页查询）
    public PageResult announcements(Integer page, Integer pagesize) {
        //调用api查询所有公告信息
        List<Announcement> list = announcementApi.findAll(page,pagesize);
        return new PageResult(page,pagesize,0l,list);
    }
}
